package cn.yuanqiao.feignService.impl;

import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.domain.BusinessActivity;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.feignService.ApiSystemService;
import cn.yuanqiao.system.domain.SysLogininfor;
import cn.yuanqiao.system.domain.SysOperLog;
import cn.yuanqiao.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static cn.yuanqiao.common.core.domain.AjaxResult.success;

/**
 * 基础服务远程调用类
 *
 * @ProjectName: cn.yuanqiao.feignService.impl
 * @ClassName: ApiSystemServerImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/7/8 17:24
 * @Version: 1.0
 **/
@Service
public class ApiSystemServiceImpl implements ApiSystemService {
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysOperLogService operLogService;
    @Autowired
    private ISysLogininforService logininforService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysRoleService roleService;
    @Value("${encryption}")
    private String encryption;


    /**
     * 根据参数键名查询参数值
     */
    @Override
    public R<AjaxResult> getConfigByKey(String configKey) {
        return R.ok(success(configService.selectConfigByKey(configKey)));
    }
    @Override
    public R<String> getConfigByKeyTenantCode(String configKey, String tenantCode) {
        return R.ok(configService.selectConfigByKeyTenantCode(configKey, tenantCode));
    }

    /**
     * 新增操作日志
     *
     * @param sysOperLog
     * @return
     * @throws Exception
     */
    @Override
    public R<Boolean> saveLog(SysOperLog sysOperLog) throws Exception {
        int i = operLogService.insertOperlog(sysOperLog);
        if (i > 0) {
            return R.ok(true);
        }
        return R.ok(false);
    }
    @Override
    public R<Boolean> saveBusinessBehavior(BusinessActivity businessActivity) throws Exception {
        int i = operLogService.insertA001Businessactivity(businessActivity);
        if (i > 0) {
            return R.ok(true);
        }
        return R.ok(false);
    }

    @Override
    public R<Boolean> saveLogininfor(SysLogininfor sysLogininfor) {
        int i = logininforService.insertLogininfor(sysLogininfor);
        if (i > 0) {
            return R.ok(true);
        }
        return R.ok(false);

    }

    /**
     * 通过用户名查询用户信息
     *
     * @return 结果
     */
    @Override
    public R<Boolean> copySysMenu(String tenantCode) {
        Boolean flag = menuService.copyMenuByTenantCode(tenantCode.replaceAll(" ", ""));
        return R.ok(flag);
    }

    /**
     * 删除菜单
     *
     * @param tenantCode
     * @return
     */
    @Override
    public R<Boolean> deleteMenuByTenantCode(@PathVariable("tenantCode") String tenantCode) {
        Boolean flag = menuService.deleteMenuByTenantCode(tenantCode);
        return R.ok(flag);
    }

    /**
     * 获取三员列表
     *
     * @param isSanyuan
     * @param tenantCode
     * @return
     */
    @Override
    public R<Long[]> getTemplateMenuIds(String isSanyuan, String tenantCode) {
        Long[] menuIds = menuService.getTemplateMenuIds(isSanyuan, tenantCode);
        return R.ok(menuIds);
    }

    /**
     * 获取部门详情
     *
     * @param deptId
     * @return
     */
    @Override
    public R<SysDept> getInfoApi(Long deptId) {
        SysDept dept = deptService.selectDeptById(deptId);
        return R.ok(dept);
    }

    /**
     * 部门同步
     *
     * @param dept
     * @return
     */
    @Override
    public R<SysDept> addAsync(SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        deptService.insertDept(dept);
        return R.ok(dept);
    }

    /**
     * 查询部门信息
     *
     * @param deptName
     * @param tenantCode
     * @return
     */
   /* public R<SysDept> getParentAsync(String deptName, String tenantCode) {
        SysDept dept = deptService.selectDeptByName(deptName, tenantCode);
        return R.ok(dept);
    }*/

    /**
     * 修改部门
     *
     * @param dept
     * @return
     */
    @Override
    public R<Integer> editAsync(SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return R.fail("该部门包含未停用的子部门！");
        }
        return R.ok(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     *
     * @param deptId
     * @return
     */
    @Override
    public R<Integer> removeAsync(Long deptId) {

        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return R.ok(deptService.deleteDeptById(deptId));
    }

    /**
     * 查询子节点信息
     *
     * @param deptName
     * @param tenantCode
     * @return
     */
    @Override
    public R<List<SysDept>> getDeptListByDeptName(String deptName, String tenantCode) {
        SysDept sysDept = new SysDept();
        sysDept.setDeptName(deptName);
        sysDept.setTenantCode(tenantCode);
        return R.ok(deptService.selectDeptListByDeptName(sysDept));
    }

    /**
     * 通过用户名查询用户信息
     *
     * @param username
     * @param tenantcode
     * @return
     */
    @Override
    public R<LoginUser> getUserInfo(String username, String tenantcode) {
        SysUser sysUser = userService.selectUserByUserName(username, tenantcode);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        Map<Long, List<Long>> menuIdsOfRoles = roleService.selectMenuIdsByRoleId(sysUser.getUserId());
        sysUser.setMenuIdsOfRoles(menuIdsOfRoles);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 用户详细信息
     *
     * @param id
     * @return
     */
    @Override
    public R<LoginUser> infoById(Long id) {
        SysUser sysUser = userService.selectUserById(id);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    @Override
    public R<LoginUser> infoByOId(String oId) {
        SysUser sysUser = userService.infoByOId(oId);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户不存在");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     *
     * @param sysUser
     * @return
     */
    @Override
    public R<Boolean> registerUserInfo(SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 新增角色信息
     *
     * @param list
     * @return
     */
    @Override
    public R<String> addSysRoles(List<SysRole> list) {
        for (int i = 0; i < list.size(); i++) {
            SysRole sysRole = list.get(i);
            Long[] muneIds = {};
            //sysRole.setMenuIds(muneIds);
            //sysRole.setTenantCode(SecurityUtils.getTenantCode());
            roleService.insertRole(sysRole);
            System.out.println(111);
            roleService.updateRole(sysRole);
        }
        return R.ok("success");
    }

    /**
     * 新增用户信息
     *
     * @param list
     * @return
     */
    @Override
    public R<String> addSysUsers(List<SysUser> list) {
        Iterator<SysUser> iterator = list.iterator();
        while (iterator.hasNext()) {
            SysUser sysUser = iterator.next();
            sysUser.setCreateBy(SecurityUtils.getUsername());
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword(), encryption));
            String tenantCode = sysUser.getTenantCode();
            String userName = sysUser.getUserName();
            String roleId = roleService.getRoleByTenantCodeAndRoleKey(tenantCode + "_" + userName, tenantCode);
            Long[] roleIdArr = {Long.valueOf(roleId)};
            Long[] postArr = {};
            sysUser.setRoleIds(roleIdArr);
            sysUser.setPostIds(postArr);
            //sysUser.setTenantCode(tenantCode);
            userService.insertUser(sysUser);
        }
        return R.ok("success");
    }

    /**
     * 查询用户信息
     *
     * @param roleKey
     * @return
     */
    @Override
    public R<String> getMenuPermission(String roleKey) {
        Set<String> set = permissionService.selectMenuPersByRoleId(roleKey);
        StringBuffer sb = new StringBuffer();
        if (set.size() > 0) {
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                sb.append(next).append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return R.ok(sb.toString());
    }

    /**
     * 删除租户信息
     *
     * @param tenantCode
     * @param source
     * @return
     */
    @Override
    public R<String> deleteTenantAbout(String tenantCode, String source) {
        List<Long> sysUsers = userService.selectUserByTenantCode(tenantCode);
        List<Long> sysRoles = roleService.selectRoleListByTenantCode(tenantCode);
        Long[] l = {};
        Long[] l2 = {};
        Long[] lo = sysUsers.toArray(l);
        Long[] lo2 = sysRoles.toArray(l2);
        userService.deleteUserByIds(lo);
        roleService.deleteRoleByIds(lo2);
        return R.ok("success");
    }

    /**
     * 查询用户信息
     *
     * @param roleKey
     * @param deptId
     * @param tenantCode
     * @return
     */
    @Override
    public R<List<SysUser>> selectSysUserByRoleKeyAndDeptId(String roleKey, String deptId, String tenantCode) {
        return R.ok(userService.selectSysUserByRoleKeyAndDeptId(roleKey, deptId, tenantCode));
    }

    /**
     * 查询用户信息
     *
     * @param roleKey
     * @param tenantCode
     * @return
     */
    @Override
    public R<List<SysUser>> selectSysUserByRoleKey(String roleKey, String tenantCode) {
        return R.ok(userService.selectSysUserByRoleKey(roleKey, tenantCode));
    }

    /**
     * 用户同步
     *
     * @param user
     * @return
     */
    @Override
    public R<SysUser> addAsync(SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userService.insertUser(user);
        return R.ok(user);
    }

    /**
     * 用户修改
     *
     * @param user
     * @return
     */
    @Override
    public R<Integer> editAsync(SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return R.ok(userService.updateUser(user));
    }

    /**
     * 查询用户信息
     *
     * @param nickName
     * @param tenantcode
     * @return
     */
    @Override
    public R<List<SysUser>> getUserByNickName(String nickName, String tenantcode) {
        SysUser sysUser = new SysUser();
        sysUser.setNickName(nickName);
        sysUser.setTenantCode(tenantcode);
        List<SysUser> userList = userService.synchronizationUserList(sysUser);
        return R.ok(userList);
    }

    /**
     * 删除用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public R<Integer> removeAsyncUser(Long userId) {
        return R.ok(userService.deleteUserById(userId));
    }

    /**
     * 查询角色信息
     *
     * @return
     */
    @Override
    public R<List<SysRole>> selectSysRoleList() {
        SysRole role = new SysRole();
        role.setTenantCode(SecurityUtils.getLoginUser().getSysUser().getTenantCode());
        List<SysRole> list = roleService.selectRoleList(role);
        return R.ok(list);
    }
    @Override
    public R<String> getAllMenuByRole(String roleId) {
        String menuIs = menuService.getAllMenuByRole(roleId);
        return R.ok(menuIs);
    }
    @Override
    public R<Map<String, String>> selectHmacByRoleId(String roleId) {
        Map<String, String> map = roleService.selectHmacByRoleId(roleId);
        return R.ok(map);
    }

    @Override
    public R changeStatusApi(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(userService.updateUserStatus(user));
    }

}
